package org.snusmumr.android.media.data;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class DatabaseProvider {
	private static final String TAG = DatabaseProvider.class.getSimpleName();
	public enum DatabaseMode {
		Read, Write
	}
	
	private static DatabaseProvider INSTANCE;
	
	public static synchronized DatabaseProvider getInstance(Context context) {
		if(INSTANCE == null)
			INSTANCE = new DatabaseProvider(context);
		return INSTANCE;
	}
	
	private SQLiteDatabase mDatabase;
	private DatabaseManager mDbManager;
	
	private DatabaseProvider(Context context, CursorFactory factory) {
		this.mDbManager = new DatabaseManager(context, factory);
	}
	
	private DatabaseProvider(Context context) {
		this(context, null);
	}
	
	public SQLiteDatabase getDatabase(DatabaseMode requestedMode) {
		Log.i(TAG, "database state: " + (mDatabase != null ? mDatabase.isOpen() : false));
		if(mDatabase == null || (!mDatabase.isOpen())) {
			// check if database object is created and opened
			openDatabase(requestedMode);
		} else {
			// check mode of opened database
			DatabaseMode currentMode = mDatabase.isReadOnly() ? DatabaseMode.Read : DatabaseMode.Write;
			if(currentMode == DatabaseMode.Read && requestedMode == DatabaseMode.Write) {
				// reopen database
				Log.i(TAG, "Reopen database sinse it was open in readonly mode");
				mDatabase.close();
				openDatabase(requestedMode);
			}
		}
		return mDatabase;
	}
	
	private void openDatabase(DatabaseMode mode) {
		switch (mode) {
		case Write:
			Log.i(TAG, "Opening database in writable mode");
			mDatabase = mDbManager.getWritableDatabase();
			break;

		default:
			Log.i(TAG, "Opening database in readonly mode");
			mDatabase = mDbManager.getReadableDatabase();
			break;
		}
	}
	
	public void close() {
		Log.i(TAG, "Closing database");
		mDatabase.close();
	}
}
